package database;

import java.util.Date;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import utility.Constants;

public final class ActivitiesRange {
	private Timestamp startTimeRange;
	private Timestamp endTimeRange;
	private final int activityId;

	public ActivitiesRange(final Date startTimeRange, final Date endTimeRange, final int activityId){
		this.startTimeRange = new Timestamp(startTimeRange.getTime());
		this.endTimeRange = new Timestamp(endTimeRange.getTime());
		this.activityId = activityId;
	}

	public double getActivityTime() {
		final Column[] whats = {Database.sessionStartTimeColumn, Database.sessionEndTimeColumn, Database.activityIdColumn};
		double counter = 0;
		try{
			final char[] operators = {'>','<','='};
			final String[] values = {startTimeRange.toString(),endTimeRange.toString(), Integer.toString(activityId)};
			final Connection con = SqlWrapper.connectToSQLite();
			final Statement st = con.createStatement();
			final ResultSet rs = st.executeQuery(SqlWrapper.select(Database.recordedSessionsTable, whats,operators,values));
			while (rs.next()){
				final Timestamp b = Timestamp.valueOf(rs.getObject(2).toString());
				final Timestamp a = Timestamp.valueOf(rs.getObject(1).toString());
				long bb = b.getTime();
				long aa = a.getTime();
				double increment = (bb-aa)/Constants.HH_MILLIS;
				if (increment > 0)
					//System.out.println("increment: " + b.toString() +" , "+ a.toString() + ": "+increment);
				counter += increment;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return counter;
	}


	public void ChangeDateRange(final Date startTimeRange, final Date endTimeRange) {
		this.startTimeRange = new Timestamp(startTimeRange.getTime());
		this.endTimeRange = new Timestamp(endTimeRange.getTime());
	}
}

